﻿using AutoMapper;
using B.S.GridManage.Api.Write.Application.Command.DutyGrid;
using B.S.GridManage.Domain.Entities;
using B.S.GridManage.ErrorCode;
using B.S.GridManage.Infrastructure.Interface;
using MediatR;
using System.Transactions;

namespace B.S.GridManage.Api.Write.Application.Handler.DutyGrid
{
    public class UpdateDutyHandler : IRequestHandler<UpdateDutyCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<DutyGridModel> dutyRepo;
        private readonly IMapper mapper;
        private readonly ILogger<UpdateDutyHandler> logger;

        /// <summary>
        /// 注入仓储和映射组件automapper
        /// </summary>
        /// <param name="dutyRepo"></param>
        /// <param name="mapper"></param>
        public UpdateDutyHandler(IBaseRepository<DutyGridModel> dutyRepo,IMapper mapper,ILogger<UpdateDutyHandler> logger)
        {
            this.dutyRepo = dutyRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(UpdateDutyCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            var model =await dutyRepo.GetModel(request.Id);
            if (model == null) {
                res.Msg = "您要求改的责任网格" + request.Id+ "不存在";
                res.Code = ApiEnum.Failed;
                return res;
            }

            model = mapper.Map(request,model);//把request里的所有属性,映射到实体中

            int r = 0;


            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) {

                try
                {
                    r = await dutyRepo.UpdateAsync(model);
                    //throw new Exception("人为抛出错误");
                    tran.Complete();//事务
                }
                catch (Exception e)
                {
                    //
                    logger.LogError("发生错误,修改责任网格已回滚:" + e.Message);
                }
            }


            if (r >0)
            {
                res.Msg = "责任网格编号编辑成功";
                res.Code = ApiEnum.Success;
                res.Data = r;               
            }
            else
            {
                res.Msg = "责任网格编号编辑失败";
                res.Code = ApiEnum.Failed;
                res.Data = r;
              
            }
            return res;


        }
    }
}
